<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\android\v12;


use app\api\model\Common;


use app\api\model\OrderModel;
use app\api\model\OrderModification;
use app\api\model\SchemeCollection;
use app\api\model\schemeMaster;
use app\api\model\Envelopes;
use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use app\api\model\Authority;


class UrbanDistrict extends Controller
{
    protected $us;

    public function _initialize()
    {
        $this->us = Authority::check(1);
    }


    /*
     * 获取小区
     */
    public function quartersList()
    {
        $city = Authority::param(['city', 'name']);

        if (Cache::get($city['city'] . 'city')) {
            $list = Cache::get($city['city'] . 'city');
        } else {
            $list = \db('house', config('database.zong'))->where('city', $city['city'])->field('id,name,city as cityId,area')->select();
            Cache::set($city['city'] . 'city', $list);
        }
        if ($city['name'] != '') {
            $arr = array();
            foreach ($list as $k => $v) {
                if (strstr($v['name'], $city['name']) !== false) {
                    array_push($arr, $v);
                }
            }
            $list = $arr;
        }

        r_date($list, 200);
    }

    /*
     * 获取户型
     * Db::connect($this->shopowner_db)->name('payment')
        ->field('orders_id,SUM(money) as payment, SUM(material) as main_payment, SUM(agency_material) as agent_payment,SUM(IF(cleared_time>0,material,0)) as main_payment_ok,SUM(IF(cleared_time>0,agency_material,0)) as agent_payment_ok')
        ->whereRaw('money>0 and IF(weixin=2,success=2,success=1) and orders_id>0')
        ->group('orders_id')
        ->buildSql();
     */
    public function HouseType(Common $common)
    {

        r_date($common->HouseData(), 200);
    }

    /*
     * 方案标签
     */
    public function programme()
    {
        $city        = Authority::param(['ids']);
        $labelList   = db('scheme_label_top', config('database.zong'))->field('id,title')->whereIn('id', $city['ids'])->whereNull('delete_time')->select();
        $schemeLabel = db('scheme_label', config('database.zong'))->field('id,title,pid,classification')->whereNull('delete_time')->select();
        foreach ($labelList as $k => $value) {
            foreach ($schemeLabel as $j => $l) {
                if ($value['id'] == $l['pid']) {
                    if ($l['classification'] == 1) {
                        $labelList[$k]['position'][] = $l;
                        foreach ($labelList[$k]['position'] as $p => $item) {
                            unset($labelList[$k]['position'][$p]['pid'], $labelList[$k]['position'][$p]['classification']);
                        }
                    }
                    if ($l['classification'] == 2) {
                        $labelList[$k]['problem'][] = $l;
                        foreach ($labelList[$k]['problem'] as $p => $item) {
                            unset($labelList[$k]['problem'][$p]['pid'], $labelList[$k]['problem'][$p]['classification']);
                        }
                    }
                }
            }
        }

        r_date($labelList, 200);
    }

    /*
     * 搜索中的方案标签
     */
    public function searchProgramme(Common $common)
    {
        $labelList     = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();
        $schemeLabel   = db('scheme_label', config('database.zong'))->field('id,title')->where('classification', 1)->group('title')->whereNull('delete_time')->select();
        $clock_in_scan = db('user_config', config('database.zong'))->where('key', 'scheme_position')->where('status', 1)->value('value');;

        r_date(['houseType' => $common->HouseData(), 'problem' => $labelList, 'schemeLabel' => $schemeLabel, 'smallScheme' => json_decode($clock_in_scan, true)], 200);
    }

    /*
     * 方案大师问题一级
     */
    public function schemeLabelTop()
    {
        $labelList = db('scheme_label_top', config('database.zong'))->field('id,title')->whereNull('delete_time')->select();


        r_date($labelList, 200);
    }

    /*
     * 方案大师创建
     */
    public function SchemeMasterCreation(OrderModification $modification)
    {
        $paper     = Request::instance()->post();
        $parameter = $paper;
        Db::connect(config('database.zong'))->startTrans();
//        $communityName = json_decode($parameter['communityName'], true);
//        $project = json_decode($parameter['project'], true);
//        $img = json_decode($parameter['img'], true);
//        $houseType = json_decode($parameter['houseType'], true);
//        $tag = json_decode($parameter['tag'], true);
//        $category = json_decode($parameter['category'], true);
        $communityName = $parameter['communityName'];
        $childId       = json_decode($parameter['childId'], true);
        $project       = $parameter['project'];
        $img           = $parameter['img'];
        $houseType     = $parameter['houseType'];
        $tag           = $parameter['tag'];
        $category      = $parameter['category'];
        if (config('city') == 'cd') {
            $city = 241;
        } elseif (config('city') == 'cq') {
            $city = 239;
        } elseif (config('city') == 'gy') {
            $city = 262;
        } elseif (config('city') == 'wh') {
            $city = 172;
        } elseif (config('city') == 'sz') {
            $city = 202;
        } elseif (config('city') == 'sh') {
            $city = 375;
        } elseif (config('city') == 'bj') {
            $city = 501;
        }
        try {
            if ($paper['schemeId'] == 0) {
                $schemeLabel = Db::connect(config('database.zong'))->table('scheme_master')->insertGetId([
                    'name' => $parameter['name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'new' => 1,
                    'private' => 1,
                    'creation_time' => time(),
                    'user_id' => $this->us['user_id'],
                    'city_id' => empty($communityName[0]['cityId']) ? $city : $communityName[0]['cityId'],
                    'area' => $communityName[0]['area'],
                    'create_city_id' => config('cityId'),
                    'scheme_no' => 'YNWX' . date('Ymdhi') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
                ]);


            } else {
                Db::connect(config('database.zong'))->table('scheme_master')->where(['plan_id' => $paper['schemeId'], 'user_id' => $this->us['user_id']])->update(['name' => $parameter['name'],
                    'info' => $parameter['info'],
                    'day' => $parameter['day'],
                    'city_id' => empty($communityName[0]['cityId']) ? $city : $communityName[0]['cityId'],
                    'area' => $communityName[0]['area'],
                ]);

                Db::connect(config('database.zong'))->table('scheme_project')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_img')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_community')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_house')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_tag')->where('plan_id', $paper['schemeId'])->delete();
                Db::connect(config('database.zong'))->table('scheme_category')->where('plan_id', $paper['schemeId'])->delete();
                $schemeLabel = $paper['schemeId'];

            }
            if (isset($paper['orderId']) && !empty($paper['orderId'])) {
                $pro_id = \db('order')->where('order_id', $paper['orderId'])->value('pro_id');
                foreach ($childId as $item) {
                    Db::connect(config('database.zong'))->table('basic_selection')->insert(['position' => $item['id'], 'title' => $item['title'], 'type' => $item['type'], 'order_id' => $paper['orderId'], 'cleared_time' => time(), 'goods_category_id' => $pro_id]);
                }
            }

            //方案大师项目添加
            foreach ($project as $value) {
                $id = Db::connect(config('database.zong'))->table('scheme_project')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'projectId' => $value['product_id'],
                    'projectMoney' => $value['prices'],
                    'projectTitle' => $value['projectTitle'],
                    'category' => 1,
                    'company' => $value['unit'],
                    'agency' => $value['agency'],
                    'to_price' => sprintf('%.2f', $value['fang'] * $value['prices']),
                    'square' => $value['fang'],
                    'remarks' => isset($value['remarks']) ? $value['remarks'] : '',
                    'grouping' => isset($value['categoryName']) ? $value['categoryName'] : '',
                    'projectOptionValueIds' => json_encode(array_column($value['specsList'], 'option_value_id')),
                ]);

                if (!empty($value['specsList'])) {

                    foreach ($value['specsList'] as $item) {
                        Db::connect(config('database.zong'))->table('scheme_project_value')->insertGetId([
                            'scheme_project_id' => $id,//单位
                            'title' => $item['option_value_title'],//方量
                            'option_value_id' => $item['option_value_id'],//单价
                            'condition' => $item['condition'],//规则
                            'price' => $item['price'],//规则
                            'artificial' => $item['artificial'],//规则
                        ]);

                    }
                }

            }


            //方案大师图片添加

            foreach ($img as $item) {
                Db::connect(config('database.zong'))->table('scheme_img')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'title' => $item['title'],
                    'path' => $item['path'],
                ]);
            }

            foreach ($communityName as $item) {
                Db::connect(config('database.zong'))->table('scheme_community')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'community' => $item['id'],
                    'name' => $item['name'],
                    'area' => $item['area'],
                ]);

            }

            foreach ($houseType as $item) {

                Db::connect(config('database.zong'))->table('scheme_house')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'house' => $item['id'],
                    'name' => $item['title'],
                ]);


            }

            foreach ($tag as $item) {

                foreach ($item['position'] as $value) {
                    Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'tag' => $value['id'],
                        'name' => $value['title'],
                        'type' => 1,
                        'pid' => $item['id'],
                    ]);
                }
                foreach ($item['problem'] as $value) {
                    Db::connect(config('database.zong'))->table('scheme_tag')->insertGetId([
                        'plan_id' => $schemeLabel,
                        'tag' => $value['id'],
                        'name' => $value['title'],
                        'type' => 2,
                        'pid' => $item['id'],
                    ]);
                }

            }
            foreach ($category as $item) {
                Db::connect(config('database.zong'))->table('scheme_category')->insertGetId([
                    'plan_id' => $schemeLabel,
                    'category_id' => $item['id'],
                    'category_name' => $item['title'],
                ]);
            }
            if (isset($parameter['isEdit']) && $parameter['isEdit'] == 1) {
                $modification->update(['status' => 1, 'plan_id' => $schemeLabel, 'update_time' => time()], ['order_id' => $parameter['orderId']]);
            }
            Db::connect(config('database.zong'))->commit();
            r_date($schemeLabel, 200);
        } catch (Exception $exception) {
            Db::connect(config('database.zong'))->rollback();
            r_date(null, 300, $exception->getMessage());
        }


    }

    /*
     * 是否全部可见
     */
    public function verification()
    {
        $city = Authority::param(['isVisible', 'schemeId']);
        if ($city['isVisible'] == 'true') {
            $private = 1;
        } else {
            $private = 0;
        }
        db('scheme_master', config('database.zong'))->where('plan_id', $city['schemeId'])->update(['private' => $private]);
        r_date(null, 200);

    }

    public function SchemeMasterCreationInfo(schemeMaster $schemeMaster)
    {
        $city = Authority::param(['id']);

        $rows = $schemeMaster->with(['schemeProject', 'schemeProject.specsList'])
            ->with('schemeImg')
            ->with('schemeCommunity')
            ->with('schemeHouse')
            ->with('city')
            ->with('county')
            ->with('user')
            ->with('schemeTag')
            ->with(['SchemeCollection' => function ($query) {
                $query->where('scheme_collection.user_id', $this->us['user_id']);
            }])
            ->with('schemeCategory')
            ->where('scheme_master.plan_id', $city['id'])
            ->find()->toArray();

        $scheme_project = $rows['scheme_project'];
        $tageList       = [];
        if ($rows['scheme_tag']) {
            $result = array();
            foreach ($rows['scheme_tag'] as $k => $v) {
                $result[$v['pid']][] = $v;
            }

            foreach ($result as $k => $list) {
                $schemeTag['id'] = $k;

                $schemeTag['position'] = $result[$k];
                unset($rows['scheme_tag']);
                $tageList[] = $schemeTag;
            }
        }

        if ($rows['scheme_project']) {
            $title  = array_unique(array_column($rows['scheme_project'], 'grouping'));
            $result = array();
            foreach ($title as $key => $info) {
                foreach ($rows['scheme_project'] as $item) {
                    $item['specsList'] = $item['specs_list'];
                    $item['allMoney']  = $item['to_price'];
                    $item['types']     = 4;
                    unset($item['specs_list']);
                    if ($info == $item['grouping']) {
                        $result[$key]['title']  = $info;
                        $result[$key]['id']     = 0;
                        $result[$key]['data'][] = $item;
                    }

                }
            }

        }

        unset($rows['scheme_project']);
        $rows['scheme_project'] = array_merge($result);
        foreach ($rows['scheme_community'] as $k => $v) {
            $rows['scheme_community'][$k]['cityId'] = $rows['city_id'];

        }

        $rows['scheme_tag']    = $tageList;
        $rows['creation_time'] = date('Y-m-d H:i:s', $rows['creation_time']);
        $rows['address']       = empty($rows['city']['city']) ? '全国' : $rows['city']['city'];
        $rows['offer']         = array_sum(array_column($scheme_project, 'to_price'));
        $scheme_house          = isset($rows['scheme_house'][0]['name']) ? $rows['scheme_house'][0]['name'] : '全部';

        if ($rows['type'] == 3) {
            $briefIntroduction = "套餐方案" . '|' . $scheme_house;
        } elseif ($rows['type'] == 2) {
            $briefIntroduction = "公司方案" . '|' . $scheme_house;
        } elseif ($rows['type'] == 1) {
            $username          = \db('admin', config('database.zong'))->where('admin_id', $rows['user_id'])->value('username');
            $briefIntroduction = "店长方案（" . $rows['user']['username'] . '）|' . $scheme_house;
            if ($rows['create_type'] == 1) {
                $briefIntroduction = "店长方案（" . $username . '）|' . $scheme_house;
            }

        }
        $rows['briefIntroduction'] = $briefIntroduction;
        $rows['collection']        = empty($rows['scheme_collection']) ? 0 : 1;
        unset($rows['scheme_collection']);
        r_date($rows, 200);

    }

    /*
     * 方案大师列表查询
     * type 等于0系统方案 1收藏方案 2使用过的方案 3预设方案   name小区  方案类别category  House户型 position位置,title 编号
     */

    public function SchemeMasterCreationList(schemeMaster $schemeMaster)
    {

        $data  = Authority::param(['type', 'name', 'category', 'House', 'position', 'title', 'smallScheme', 'isShowCompany','page','limit']);
        $order = Request::instance()->post();;
        $house    = json_decode($data['House'], true);
        $house    = !empty($house) ? array_column($house, 'id') : '';
        $name     = json_decode($data['name'], true);
        $name     = !empty($name) ? array_column($name, 'id') : '';
        $position = json_decode($data['position'], true);
        $position = !empty($position) ? array_column($position, 'title') : '';
        $category = json_decode($data['category'], true);
        $category = !empty($category) ? array_column($category, 'id') : '';

        $smallScheme = json_decode($data['smallScheme'], true);
        $smallScheme = !empty($smallScheme) ? array_column($smallScheme, 'id') : '';
        $pos         = [];
        $house_id    = [];
        $rows        = $schemeMaster
            ->join('city', 'city.city_id=scheme_master.city_id', 'left')
            ->join('county', 'county.county_id=scheme_master.area', 'left')
            ->join('user', 'user.user_id=scheme_master.user_id and scheme_master.create_type=0', 'left')
            ->join('admin', 'admin.admin_id=scheme_master.user_id and scheme_master.create_type=1', 'left');

        if (isset($order['orderId']) && $order['orderId'] != 0) {
            $scheme_category = db('cc_scheme_label', config('database.zong'))->join('scheme_label_top', 'scheme_label_top.pid=cc_scheme_label.pro_id', 'left')
                ->where('order_id', $order['orderId'])
                ->field('scheme_label_top.id as topId,cc_scheme_label.*')
                ->select();

            $pos = array_column($scheme_category, 'topId');

            $house_id = array_column($scheme_category, 'house_id');

//            foreach ($scheme_category as $p) {
//                if($p['select']==1){
//                    $pos[] = $p['topId'];
//                }
//
//            }
        }
        if (!empty($pos)) {
            $scheme_category = db('scheme_category', config('database.zong'));
            $scheme_category->whereIn('category_id', $pos)->group('plan_id');
            $scheme_category = $scheme_category->column('plan_id');

            if (!empty($scheme_category)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_category);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        if (!empty($house_id)) {
            $scheme_community          = db('scheme_community', config('database.zong'))->whereIn('community', $house_id)->group('plan_id')->column('plan_id');
            $scheme_communityUnlimited = db('scheme_community', config('database.zong'))->where('community', 0)->group('plan_id')->column('plan_id');
            $scheme_community          = array_merge($scheme_community, $scheme_communityUnlimited);
            if (!empty($scheme_community)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_community);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }
        if (!empty($category)) {

            $scheme_category = db('scheme_category', config('database.zong'));
            $scheme_category->whereIn('category_id', $category)->group('plan_id');
            $scheme_category = $scheme_category->column('plan_id');

            if (!empty($scheme_category)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_category);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        /*
         * 方案大师适用户型
         */
        if (!empty($house)) {
            $nameCount = implode($house, ',');
            if ($nameCount == 9) {
                $schemeHouse = db('scheme_house', config('database.zong'))->group('plan_id')->column('plan_id');
            } else {
                $schemeHouse = db('scheme_house', config('database.zong'))->whereIn('house', $house)->group('plan_id')->column('plan_id');
            }
            if (!empty($schemeHouse)) {
                $rows->whereIn('scheme_master.plan_id', $schemeHouse);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }

        if (!empty($position)) {
            $schemeTag = [];
            foreach ($position as $item) {
                $schemeTag[] = db('scheme_tag', config('database.zong'))
                    ->where(['name' => ['like', "%{$item}%"]])->group('plan_id')->column('plan_id');
            }
            $schemeTag = array_reduce($schemeTag, 'array_merge', array());
            if (!empty($schemeTag)) {
                $rows->whereIn('scheme_master.plan_id', $schemeTag);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }

        }
        /*
         * 方案大师适小区
         */
        if (!empty($name)) {
            $nameCount = implode($name, ',');
            if ($nameCount == 0) {
                $scheme_community = db('scheme_community', config('database.zong'))->group('plan_id')->column('plan_id');

            } else {
                $scheme_community = db('scheme_community', config('database.zong'))->whereIn('community', $name)->group('plan_id')->column('plan_id');
            }
            if (!empty($scheme_community)) {
                $rows->whereIn('scheme_master.plan_id', $scheme_community);
            } else {
                $rows->whereIn('scheme_master.plan_id', '');
            }
        }

        if ($data['title'] != '') {
            $scheme_community = db('scheme_community', config('database.zong'))->where('name', 'like', "%{$data['title']}%")->group('plan_id')->column('plan_id');
            $rows->where(function ($query) use ($data, $scheme_community) {
                $query->whereIn('scheme_master.plan_id', $scheme_community)->whereOr('scheme_master.scheme_no', 'like', "%{$data['title']}%")->whereOr('scheme_master.name', 'like', "%{$data['title']}%");
            });


        }
//        if (config('city') == 'cd') {
//            $city = 241;
//        } elseif (config('city') == 'wh') {
//            $city = 172;
//        } elseif (config('city') == 'gy') {
//            $city = 262;
//        } elseif (config('city') == 'cq') {
//            $city = 239;
//        }
        if ($data['isShowCompany'] == 1) {
            $rows->where('scheme_master.type', 2);
        }

        if ($data['type'] == 0) {
            $rows->where('scheme_master.type', 3);

            if ($smallScheme != '') {
                $rows->whereIn('scheme_master.position', $smallScheme);
            }

        } elseif ($data['type'] == 1) {
            $rows->where(function ($query) {
                $query->where('scheme_master.private', 1)->whereOr('scheme_master.user_id', $this->us['user_id']);;

            })->where('scheme_master.type', '<>', 3);;
        } elseif ($data['type'] == 2) {
            $rows->join('scheme_collection', 'scheme_master.plan_id=scheme_collection.plan_id', 'right')
                ->whereNull('scheme_collection.delete_time')
                ->where('scheme_collection.user_id', $this->us['user_id']);
        } elseif ($data['type'] == 3) {
            $rows->join('scheme_use', 'scheme_master.plan_id=scheme_use.plan_id', 'right')
                ->where('scheme_use.user_id', $this->us['user_id'])
                ->group('scheme_use.plan_id');

        } elseif ($data['type'] == 4) {
            $rows->where('scheme_master.user_id', $this->us['user_id']);
        }

        $rows = $rows->field('scheme_master.*,FROM_UNIXTIME(scheme_master.creation_time) as creationTime,city.city,county.county,if(scheme_master.create_type=0,user.username,admin.username) as username')->where('scheme_master.state', 1)->where('scheme_master.new', 1)
//            ->where('scheme_master.type', 1)
            ->group('plan_id')
            ->order('scheme_master.plan_id desc')
            ->page($data['page'],$data['limit'])
            ->select();


        $array = [];
        foreach ($rows as $k => $list) {

            $tolerable['address']      = empty($list['city']) ? '全国' : $list['city'];
            $tolerable['img']     = $list->schemeImg;
            $tolerable['creationTime'] = $list['creationTime'];
            $tolerable['id']           = $list['plan_id'];
            $tolerable['title']        = $list['name'];
            $scheme_house              = isset($list['scheme_house'][0]['name']) ? $list['scheme_house'][0]['name'] : '全部';
            if ($list['type'] == 3) {
                $briefIntroduction = "套餐方案" . '|' . $scheme_house;
            } elseif ($list['type'] == 2) {
                $briefIntroduction = "公司方案" . '|' . $scheme_house;
            } elseif ($list['type'] == 1) {
                $briefIntroduction = "店长方案（" . $list['username'] . '）|' . $scheme_house;

            }
            $tolerable['briefIntroduction']  = $briefIntroduction;
            $tolerable['scheme_tag']         = $list['scheme_tag'];
            $tolerable['ConstructionPeriod'] = $list['day'];
            $tolerable['agency']             = empty(Db::connect(config('database.zong'))->table('scheme_project')->where('plan_id', $list['plan_id'])->where('agency', 1)->count()) ? 0 : 1;
            $tolerable['offer']              = array_sum(array_column($list['scheme_project'], 'to_price'));
            $array[]                         = $tolerable;
        }
        r_date($array, 200, isset($order['orderId']) ? $order['orderId'] : 0);

    }

    /*
     * 收藏
     */
    public function Collection(SchemeCollection $schemeCollection)
    {
        $data = Authority::param(['id']);
        if (config('city') == 'cd') {
            $city = 241;
        } elseif (config('city') == 'wh') {
            $city = 172;
        } elseif (config('city') == 'gy') {
            $city = 262;
        } elseif (config('city') == 'cq') {
            $city = 239;
        }
        $Collection = $schemeCollection::all(['plan_id' => $data['id'], 'user_id' => $this->us['user_id'], 'city' => $city]);

        if ($Collection) {
            foreach ($Collection as $item) {
                $res = $schemeCollection::destroy($item->id);
            }

        } else {
            $res = $schemeCollection::create([
                'plan_id' => $data['id'],
                'creation_time' => time(),
                'city' => $city,
                'user_id' => $this->us['user_id'],
            ]);
        }
        if ($res) {
            r_date(null, 200);
        } else {
            r_date(null, 300);
        }

    }

    /*
     * 方案大师交互标准
     */
    public function getCustomList()
    {
        $data        = Request::instance()->post();
        $capital     = json_decode($data['projects'], true);
        $capitalList = [];
        foreach ($capital as $k => $item) {
            $capitalList[$k]['class_b']       = $item['projectTitle'];
            $capitalList[$k]['capital_id']    = 0;
            $capitalList[$k]['auxiliary_id']  = $item['projectId'];
            $capitalList[$k]['auxiliary_ids'] = '';
            $serial                           = db('detailed')->where('detailed_id', $item['projectId'])->value('serial');
            $auxiliary_relation               = db('auxiliary_relation')
                ->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_relation.auxiliary_interactive_id and  auxiliary_interactive.parents_id=0', 'left')
                ->where('auxiliary_relation.serial_id', $serial)
                ->where('auxiliary_interactive.pro_types', 0)
                ->field('auxiliary_interactive.title,auxiliary_interactive.id')
                ->select();

            if ($auxiliary_relation) {
                foreach ($auxiliary_relation as $l => $key) {
                    $capitalList[$k]['data'][] = [
                        'id' => $key['id'],
                        'title' => $key['title'],
                    ];
                    $auxiliary_interactive     = db('auxiliary_interactive')
                        ->whereIn('auxiliary_interactive.parents_id', $key['id'])
                        ->field('auxiliary_interactive.id, auxiliary_interactive.title')->select();
                    foreach ($auxiliary_interactive as $p => $value) {

                        $auxiliary_interactive[$p]['state']                          = 3;
                        $auxiliary_interactive[$p]['node_id']                        = 0;
                        $auxiliary_interactive[$p]['auxiliary_delivery_schedule_id'] = 0;

                    }
                    $capitalList[$k]['data'][$l]['data'] = array_merge($auxiliary_interactive);
                }
            } else {
                $capitalList[$k]['data'] = [];
            }

        }
        r_date(array_values($capitalList), 200);
    }

    /*
     * 方案改造
     */
    public function SchemeMasterCreationInfoRemodel(Envelopes $envelopes, OrderModel $orderModel)
    {
        $city = Authority::param(['order_id']);
        if (empty($city['order_id'])) {
            r_date(null, 300, '参数不能为空');
        }
        $envelopes = $envelopes->with(['CapitalList', 'CapitalList.specsList',])
            ->where(['type' => 1, 'ordesr_id' => $city['order_id']])
            ->find();
        $rows      = null;
        if (!empty($envelopes)) {
            $result   = array();
            $tageList = [];
            foreach ($envelopes['capital_list'] as $k => $v) {
                $v['specsList']    = $v['specs_list'];
                $v['square']       = 0;
                $v['allMoney']     = 0;
                $v['categoryName'] = empty($v['categoryName']) ? "默认分组" : $v['categoryName'];
                unset($v['specs_list']);
                $result[$v['categoryName']][] = $v;
            }

            foreach ($result as $k => $list) {
                $schemeTag['title'] = $k;
                $schemeTag['id']    = 0;
                $schemeTag['data']  = $result[$k];
                $tageList[]         = $schemeTag;
            }
            unset($envelopes['capital_list']);

            $orderInfo                 = $orderModel
                ->join('goods_category', 'order.pro_id=goods_category.id', 'left')
                ->join('city', 'order.city_id=city.city_id', 'left')
                ->where('order_id', $city['order_id'])->field('concat(order.residential_quarters,goods_category.title) as title,order.city_id,order.county_id,city.city')
                ->find();
            $rows['name']              = $orderInfo['title'];
            $rows['type']              = 1;
            $rows['info']              = '';
            $rows['day']               = $envelopes['gong'];
            $rows['city_id']           = $orderInfo['city_id'];
            $rows['city']              = $orderInfo['city'];
            $rows['county']            = 0;
            $rows['address']           = '';
            $rows['briefIntroduction'] = '';
            $rows['collection']        = 0;
            $rows['offer']             = 0;
            $rows['area']              = 0;
            $rows['user']              = null;
            $rows['private']           = 1;
            $rows['state']             = 1;
            $rows['reminde']           = null;
            $rows['pricing_rules']     = null;
            $rows['service_content']   = null;
            $rows['materials_used']    = null;
            $rows['service_duration']  = null;
            $rows['completion']        = null;
            $rows['quality']           = null;
            $resource_ids              = Db::connect(config('database.db2'))->table('app_user_order_node')->where('order_id', $city['order_id'])->order('id desc')->field('resource_ids,title')->select();
            $pathId                    = implode(array_column($resource_ids, 'resource_ids'), ',');
            $dataList                  = [];
            if ($pathId) {
                $path = Db::connect(config('database.db2'))->table('common_resource')->where('status', 1)->whereIn('id', $pathId)->field('mime_type,path,id')->select();
                $paths=[];
                foreach ($path as $k => $o) {
                    $mime_type = explode("/", $o['mime_type'])[0];
                    if ($mime_type == 'image') {
                        $paths[$k]['path'] = 'https://images.yiniao.co/' . $o['path'];
                        $paths[$k]['id']   = $o['id'];
                    }
                }
                $resourceIdsArray=[];
                foreach ($resource_ids as $item) {
                    $resource_ids=explode(',',$item['resource_ids']);

                    foreach ($resource_ids as  $k =>$list){
                        $resourceIds['title']=$item['title'];
                        $resourceIds['id']=$list;
                        $resourceIdsArray[]=$resourceIds;
                    }
                }
                if(!empty($paths)){
                    foreach ($resourceIdsArray as $item){
                        foreach ($paths as $l) {
                            if ($l['id'] == $item['id']) {
                                $data['path']    = $l['path'];
                                $data['title']   = $item['title'];
                                $data['plan_id'] = 0;
                                $dataList[] = $data;
                            }

                        }
                    }
                }

            }




            $rows['scheme_img']       = $dataList;
            $rows['scheme_community'] = [];
            $rows['scheme_house']     = [];
            $rows['scheme_category']  = [];
            $rows['scheme_project']   = $tageList;
            $rows['scheme_tag']       = [];
        }

        r_date($rows, 200);

    }

    /*
     * 改造列表
     */
    public function reformListTitle(OrderModification $modification)
    {
        $rows['TobeTransformed'] = [
            'title' => '待改造列表',
            'type' => 1,
            'count' => $modification->where('user_id', $this->us['user_id'])->where('status', 0)->count(),
        ];
        $rows['Transformed']     = [
            'title' => '已改造列表',
            'type' => 2,
            'count' => $modification->where('user_id', $this->us['user_id'])->where('status', 1)->count(),
        ];
        $list                    = $modification->Ranking();

        $last_names              = array_search($this->us['user_id'], array_column($list, 'user_id'));
        $rows['speedOfProgress'] = [
            'title' => '进度排行榜',
            'type' => 3,
            'count' => $last_names + 1,
        ];
        r_date($rows, 200);
    }

    /**
     * 改造数据列表
     */
    public function reformList(OrderModel $orderModel, OrderModification $modification)
    {
        set_time_limit(0);

        $user = \db('user')
            ->join('store', 'store.store_id=user.store_id', 'left')
            ->where('user.status', 0)
            ->where('user.quit_jobs', 0)
            ->where('user.ce', 1)
            ->field('user.username,user.user_id,store.store_name')
            ->select();

        foreach ($user as $item) {
            $order_id=$modification->where('user_id',$item['user_id'])->column('order_id');
            $capital   = db('capital')
                ->field('sum(to_price) as to_price,ordesr_id')
                ->where(['capital.types' => 1, 'capital.enable' => 1])
                ->where('capital.fen', '<>', 4)
                ->where('capital.agency', 0)
                ->group('ordesr_id')
                ->buildSql();
            $envelopes = db('envelopes')
                ->field('sum(envelopes.give_money) as give_money,sum(envelopes.expense) as expense,ordesr_id')
                ->where(['envelopes.type' => 1])
                ->group('ordesr_id')
                ->buildSql();

            $list        = $orderModel
                ->join([$envelopes => 'envelopes'], 'envelopes.ordesr_id=order.order_id', 'right')
                ->join([$capital => 'capital'], 'capital.ordesr_id=order.order_id', 'right')
                ->join('order_aggregate', 'order_aggregate.order_id=order.order_id', 'right')
                ->join('province p', 'order.province_id=p.province_id', 'left')
                ->join('city c', 'order.city_id=c.city_id', 'left')
                ->join('county y', 'order.county_id=y.county_id', 'left')
                ->join('goods_category go', 'order.pro_id=go.id', 'left')
                ->where('assignor', $item['user_id'])
                ->where('order.state', 7)
                ->where('order.pro_id', 3)
                ->whereNotIn('order.order_id', $order_id)
                ->whereBetween('order.finish_time', [1609430400,1640966400])
                ->where('(capital.to_price + (envelopes.expense-envelopes.give_money)-ifnull(order_aggregate.reimbursement_price,0)-ifnull(order_aggregate.material_price,0)-order_aggregate.master_price)/(capital.to_price + (envelopes.expense-envelopes.give_money)) > 0.4')
                ->field('concat(p.province,c.city,ifnull(y.county," "),order.addres) as addres,order.order_id,go.title,concat(order.contacts,"(",order.telephone,")") as contacts,FROM_UNIXTIME(order.created_time,"%Y-%m-%d %H:%i:%s") as created_time,order.assignor')
                ->group('order.order_id')
                ->limit(0, 30)
                ->select();
            $orderListTi = [];
            foreach ($list as $items) {
                $orderListTi[] = [
                    'user_id' => $items['assignor'],
                    'order_id' => $items['order_id'],
                    'addres' => $items['addres'],
                    'contacts' => $items['contacts'],
                    'username' => $item['username'],
                    'title' => $items['title'],
                    'store_name' => $item['store_name'],
                    'status' => 0,
                    'type' => 1,
                ];
            }
            $modification->saveAll($orderListTi);
        }


        r_date($list, 200);


    }

    /*
     * 进度排行榜
     */
    public function RankingList(OrderModification $modification)
    {
        $data = Authority::param(['type']);
        switch ($data['type']) {
            case 1:
                $list = $modification->where('order_modification.status', 0)->join('order', 'order_modification.order_id=order.order_id', 'left')->field('order_modification.id,order_modification.order_id,order_modification.user_id,order_modification.addres,order_modification.contacts,order_modification.type,order_modification.username,order_modification.store_name,order_modification.title,order.state as status,order.created_time')->where('user_id', $this->us['user_id'])->select();
                break;
            case 2:
                $list = $modification->where('order_modification.status', 1)->join('order', 'order_modification.order_id=order.order_id', 'left')->field('order_modification.id,order_modification.order_id,order_modification.user_id,order_modification.addres,order_modification.contacts,order_modification.type,order_modification.username,order_modification.store_name,order_modification.title,order.state as status')->where('user_id', $this->us['user_id'])->select();
                break;
            default:
                $list = $modification->Ranking();

        }
        r_date($list, 200);

    }


}